package main;

import java.util.concurrent.*;

/**
 * @author Xu,
 * @data 2020/11/24，
 * @time 12:30
 * 4线程处理
 */
public class FourThread {
    private double sf = 1.0;
    private double pi = 0.0;
    private double item = 1.0;
    private double den = 1.0;
    private double sf1 = -1.0;
    private double item1 = -1/3.0;
    private double den1 = 3.0;
    private double pi1 = 0.0;
    private double sf2 = 1.0;
    private double pi2 = 0.0;
    private double item2 = 1/5.0;
    private double den2 = 5.0;
    private double sf3 = -1.0;
    private double item3 = -1/7.0;
    private double den3 = 7.0;
    private double pi3 = 0.0;
    private final double MAX = 1e-10;
    public FourThread(){
        long start = System.currentTimeMillis();
        ExecutorService executorService = new ThreadPoolExecutor(4, 4, 0L,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(10),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                while (Math.abs(item) >= MAX) {
                    pi += item;
                    den += 8;
                    item = sf / den;
                }
            }
        });
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                while (Math.abs(item1) >= MAX) {
                    pi1 += item1;
                    den1 += 8;
                    item1 = sf1 / den1;
                }
            }
        });
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                while (Math.abs(item2) >= MAX) {
                    pi2 += item2;
                    den2 += 8;
                    item2 = sf2 / den2;
                }
            }
        });
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                while (Math.abs(item3) >= MAX) {
                    pi3 += item3;
                    den3 += 8;
                    item3 = sf3 / den3;
                }
            }
        });
        executorService.shutdown();
        while(!executorService.isTerminated()){ }
        pi = 4*(pi+pi1+pi2+pi3);
        //System.out.println("pi的值为: "+ pi);
        long end = System.currentTimeMillis();
        System.out.println("runtime: " + (end - start)/1000.0+"s");
    }
}
